<template>
	<view>
		<!-- 加载中蒙版 -->
		<uni-transition mode-class="fade" :duration="500" :show="!dataLoaded" custom-class="vague-bg-9 mask-load">
		</uni-transition>
		<!-- #ifdef MP-WEIXIN -->
		<!-- 顶部导航 -->
		<custom-navber :title="'发布圈子'"></custom-navber>
		<!-- #endif -->
		<view :style="{paddingTop:menuObject.top + menuObject.height + 15 +'px'}" class="ping-30">
			<!-- 图片上传 -->
			<uni-file-picker ref="files" v-model="imgUrl" return-type="array" limit="6" mode="grid"
				file-mediatype="image" :sizeType="['compressed']"
				:image-styles="{width: '160rpx', height: '160rpx',border:false,background:'#f7f7f7',borderRadius:'20rpx',lineHeight:'160rpx'}">
			</uni-file-picker>
			<!-- 标题输入 -->
			<view class="input-box ali-item-cen flex-dir-row ali-item-cen flex-x-bet">
				<input confirm-type="done" placeholder-class="input-placeholder" type="text" v-model="title"
					placeholder="填写标题" cursor-color="#14cc60" :maxlength="23" class="w-100 fs-32 fw-600" />
				<text v-if="title" class="iconfont ic-qingchu fs-40 col-b1 mr-20 ml-20" @click="clearTitle"></text>
				<view class="fs-26 col-b1">{{23-title.length}}</view>
			</view>
			<!-- 多行内容输入 -->
			<view class="mt-30 textarea-box">
				<textarea placeholder-class="textarea-placeholder" :maxlength="230" v-model="content" placeholder="填写内容"
					cursor-color="#14cc60" class="w-100 fs-30" />
			</view>
			<view class="mt-30">
				<view class=" w-100 mt-30 bac-col-f ping-30-0 activity-box">
					<view class="w-100 flex-dir-row ali-item-cen flex-x-bet">
						<view class="fs-28 fw-600">关联活动</view>
						<view class="bor-bottom-f3 br-200 bac-col-f text-ali-c ping-0-20 fs-26" style="width: 340rpx;">
							<input type="text" v-model="activityName" confirm-type="done"
								placeholder-style="color:#b1b1b1;font-size:26rpx;text-align:center;"
								placeholder="输入活动名称查找" />
						</view>
					</view>
					<scroll-view scroll-x class="w-100 mt-20">
						<view class="flex-dir-row">
							<view class="flex-dir-row ali-item-cen mr-20 flex-shrink-0"
								v-for="(item, index) in filteredActivityList" :key="index"
								@click="activityClick(item._id)">
								<view style="height: 55rpx;line-height: 55rpx;"
									:class="selectedActivity === item._id ? 'bac-col-00b col-f' : 'activity-item'"
									class="br-10 flex-dir-row ali-item-cen pr-20">
									<image :src="item.imgs[0].src || ''"
										style="width: 55rpx; height: 55rpx;border-top-left-radius: 10rpx;border-bottom-left-radius: 10rpx;"
										mode="aspectFill" />
									<view class="fs-28 ml-20 text-element-1 flex-1">{{ item.name }}</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</view>
		<!-- 底部定位发布按钮 -->
		<view class="w-100 fixed-bottom bac-col-00b" @click="publish">
			<view class="w-100 bg-col-00b text-ali-c">
				<view class="fs-30 col-f fw-600">发布圈子</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: '', // 标题
				content: '', // 内容
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif // 菜单按钮位置
				selectedActivity: '', // 选中的活动id
				imgUrl: [], // 图片上传
				activityList: [], // 活动列表
				activityName: '', // 搜索框输入的内容
				circleId: '', // 圈子id
				dataLoaded: false, // 数据是否加载完成
			};
		},
		computed: {
			// 计算筛选后的活动列表
			filteredActivityList() {
				if (!this.activityName.trim()) {
					// 如果输入框为空，返回全部列表
					return this.activityList;
				}
				const searchText = this.activityName.toLowerCase(); // 转换为小写
				return this.activityList.filter(item => item.name.toLowerCase().includes(searchText));
			}
		},
		onLoad(e) {
			if (e.id) {
				this.circleId = e.id;
				// 如果存在圈子id则为修改，获取圈子详情
				this.getCircleDetail();
			}
			// 获取活动列表
			this.getActivityList();
		},
		methods: {
			// 获取圈子详情
			getCircleDetail() {
				this.$Route('get-private-data').getMyCircleDetail(this.circleId).then((res) => {
					this.circleData = res.data[0];
					this.imgUrl = res.data[0].imgs_info;
					this.title = res.data[0].title;
					this.content = res.data[0].content;
					this.selectedActivity = res.data[0].activity_id;
					if (!this.circleData.imgs_info) {
						this.$Toast('该圈子为管理端发布，请到管理端编辑');
						setTimeout(() => this.$NavigateBack(), 1600)
						return;
					}
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
				});
			},
			// 获取活动列表
			getActivityList() {
				this.$Route('get-public-data').getActivityData({
					name: ''
				}).then((res) => {
					this.activityList = res.data;
					this.dataLoaded = true;
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					this.dataLoaded = true;
				});
			},
			// 选中活动
			activityClick(id) {
				this.selectedActivity = id;
			},
			// 发布圈子
			async publish() {
				this.$debounce(async () => {
					// 震动
					uni.vibrateShort();
					// 先校验用户所有参数，如果参数不完整，返回并提示用户
					if (this.imgUrl.length == 0) {
						this.$Toast('请上传图片');
						return;
					}
					if (this.title.trim() == '') {
						this.$Toast('请填写标题');
						return;
					}
					if (this.content.trim() == '') {
						this.$Toast('请填写内容');
						return;
					}
					// 如果存在圈子id，则为修改
					if (this.circleId) {
						this.updateCircle();
					} else {
						this.addCircle();
					}
				}, 500, true, "publish")
			},
			// 修改圈子
			async updateCircle() {
				await this.$Route('update-private-data').updateCircleData({
					id: this.circleId,
					title: this.title,
					content: this.content,
					activityId: this.selectedActivity,
					imgs: this.imgUrl
				}).then((res) => {
					this.$Toast(res.msg);
					this.getOpenerEventChannel().emit('refreshData', '')
					setTimeout(() => this.$NavigateBack(), 1000)
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				});
			},
			// 添加圈子
			async addCircle() {
				await this.$Route('add-private-data').addCircleData({
					title: this.title,
					content: this.content,
					activityId: this.selectedActivity,
					imgs: this.imgUrl
				}).then((res) => {
					this.$Toast(res.msg);
					setTimeout(() => {
						this.$NavigateTo('/pages/index/index');
					}, 1000);
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				});
			}
		}
	};
</script>

<style lang="scss">
	.upload-image {
		width: 170rpx;
		height: 170rpx;

		.upload-image-item {
			line-height: 170rpx;
		}
	}

	.input-box {
		width: 100%;
		height: 90rpx;
		border-bottom: 1rpx solid #f3f3f3;
	}

	.input-placeholder {
		font-size: 30rpx;
		color: #b1b1b1;
		font-weight: normal;
	}

	.textarea-placeholder {
		font-size: 28rpx;
		color: #b1b1b1;
		font-weight: normal;
	}

	.textarea-box {
		height: 300rpx;
	}

	.activity-box {
		border-top: 1rpx solid #f3f3f3;
	}

	.activity-item {
		border-radius: 10rpx;
		background-color: #f7f7f7;
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		padding-top: 30rpx;
		padding-bottom: 30rpx !important;
		padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)) !important;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom)) !important;
		z-index: 9999;
		transition: background-color 0.2s ease;
	}

	.fixed-bottom:active {
		background-color: #11b051 !important;
		/* 点击时背景颜色变化 */
	}

	textarea {
		height: 300rpx !important;
	}
</style>